package web;

import app.PropertiesConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import sun.plugin.javascript.navig.JSType;
import web.intecetptor.TestInterceptor;

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {
    private PropertiesConfig propertiesConfig;
    public WebConfig(PropertiesConfig propertiesConfig){
        this.propertiesConfig=propertiesConfig;
    }

    /**
     * 配置视图解析器
     * @return
     */
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setSuffix(propertiesConfig.getSpringWebMvcViewSuffix());
        viewResolver.setPrefix(propertiesConfig.getSpringWebMvcViewPrefix());
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

    /**
     * 配置静态资源的方法
     * 1) addResourceHandler：遇到请求路径:/static/**的交给ResourceHandler处理
     * 2) addResourceLocations :去哪里找资源文件
     * 3）setCachePeriod:设置静态资源缓存时间
     * @param registry
     */
   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler(
               propertiesConfig.getSpringMvcStaticResourceHandler()).
               addResourceLocations(propertiesConfig.getSpringMvcStaticResourceLocation()).
               setCachePeriod(propertiesConfig.getSpringMvcStaticResourceCachePeriod() * 30);

   }
   @Override
    public void addInterceptors(InterceptorRegistry registry){
       registry.addInterceptor(new TestInterceptor()).addPathPatterns("/user/**");
   }
    /**
     * 相关属性一定移到application.properties当中
     * 做上传文件的处理
     *
     * @return
     */
   @Bean
    public MultipartResolver multipartResolver(){
       CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
       commonsMultipartResolver.setDefaultEncoding("UTF-8");
       return commonsMultipartResolver;
   }
   @Bean
    public RestTemplate restTemplate(){return new RestTemplate();}

}
